package com.hrsoft.modules.sys.service.impl;

import com.hrsoft.modules.sys.dto.DepartmentTreeDto;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hrsoft.common.utils.PageUtils;
import com.hrsoft.common.utils.Query;

import com.hrsoft.modules.sys.dao.SysDepartmentDao;
import com.hrsoft.modules.sys.entity.SysDepartmentEntity;
import com.hrsoft.modules.sys.service.SysDepartmentService;


@Service("sysDepartmentService")
public class SysDepartmentServiceImpl extends ServiceImpl<SysDepartmentDao, SysDepartmentEntity> implements SysDepartmentService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SysDepartmentEntity> queryWrapper = new QueryWrapper<>();
        if (params.get("key") != null && StringUtils.isNotBlank(params.get("key").toString())) {
            queryWrapper.like("name", "%" + params.get("key").toString() + "%");
        }
        if (params.get("parentId") != null && params.get("parentId").toString() != "0") {
            queryWrapper.eq("parent_id", params.get("parentId"));
        }

        IPage<SysDepartmentEntity> page = this.page(
            new Query<SysDepartmentEntity>().getPage(params),
            queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<DepartmentTreeDto> getTreeList (Integer parentId) {
        List<DepartmentTreeDto> treeList = new ArrayList<>();
        QueryWrapper<SysDepartmentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);
        List<SysDepartmentEntity> departList = this.list(wrapper);
        DepartmentTreeDto tmpDepartTree = null;
        if (departList.size() <= 0) {
            return null;
        }
        for (SysDepartmentEntity tmpDepart : departList) {
            tmpDepartTree = new DepartmentTreeDto();
            tmpDepartTree.setId(tmpDepart.getId().intValue());
            tmpDepartTree.setLabel(tmpDepart.getName());
            tmpDepartTree.setChildren(this.getTreeList(tmpDepart.getId().intValue()));
            treeList.add(tmpDepartTree);
        }
        return treeList;
    }

}